package com.tudouji.project.mt.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.framework.task.MeituanDataProcessUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.bill.domain.Whinform;
import com.tudouji.project.bill.domain.Whinformitem;
import com.tudouji.project.bill.mapper.WhinformMapper;
import com.tudouji.project.bill.mapper.WhinformitemMapper;
import com.tudouji.project.mt.domain.*;
import com.tudouji.project.mt.mapper.MtWhinMapper;
import com.tudouji.project.mt.mapper.MtWhinitemMapper;
import com.tudouji.project.mt.service.*;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.organization.mapper.SupplierMapper;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.purchasebill.domain.Purchasebill;
import com.tudouji.project.purchasebill.domain.Purchasebillitem;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.mapper.StorehouseroomMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.ISysConfigService;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tudouji.project.mt.mapper.MtShopMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import static com.tudouji.common.utils.DateUtils.YYYYMMDD;
import static com.tudouji.project.mt.domain.MtShop.sell_state;

/**
 * 美团店铺Service业务层处理
 *
 * @author tudouji
 * @date 2023-11-21
 */
@Service
@Slf4j
public class MtShopServiceImpl implements IMtShopService {
    @Autowired
    private MtShopMapper mtShopMapper;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IMtWhinService mtWhinService;
    @Autowired
    private IMtWhoutService mtWhoutService;
    @Autowired
    private IMtSalesService mtSalesService;
    @Autowired
    private MtFoodconsumServiceImpl mtFoodconsumService;
    @Autowired
    private IMtFoodcostcardService mtFoodcostcardService;
    @Autowired
    private IMtTokenService iMtTokenService;

    /**
     * 查询美团店铺
     *
     * @param id 美团店铺ID
     * @return 美团店铺
     */
    @Override
    public MtShop selectMtShopById(Long id) {
        return mtShopMapper.selectMtShopById(id);
    }

    /**
     * 查询美团店铺列表
     *
     * @param mtShop 美团店铺
     * @return 美团店铺
     */
    @Override
    public List<MtShop> selectMtShopList(MtShop mtShop) {
        return mtShopMapper.selectMtShopList(mtShop);
    }

    /**
     * 新增美团店铺
     *
     * @param mtShop 美团店铺
     * @return 结果
     */
    @Override
    public int insertMtShop(MtShop mtShop) {
        mtShop.setCreateTime(DateUtils.getNowDate());
        return mtShopMapper.insertMtShop(mtShop);
    }

    /**
     * 修改美团店铺
     *
     * @param mtShop 美团店铺
     * @return 结果
     */
    @Override
    public int updateMtShop(MtShop mtShop) {
        mtShop.setUpdateTime(DateUtils.getNowDate());
        return mtShopMapper.updateMtShop(mtShop);
    }

    /**
     * 批量删除美团店铺
     *
     * @param ids 需要删除的美团店铺ID
     * @return 结果
     */
    @Override
    public int deleteMtShopByIds(Long[] ids) {
        return mtShopMapper.deleteMtShopByIds(ids);
    }

    /**
     * 删除美团店铺信息
     *
     * @param id 美团店铺ID
     * @return 结果
     */
    @Override
    public int deleteMtShopById(Long id) {
        return mtShopMapper.deleteMtShopById(id);
    }


    public Date getBizTimeEnd(MtShop shop) {
        String overDate = sysConfigService.selectConfigByKey("over_date");
        Date bizTimeLastEnd = MeituanDataProcessUtil.getLoadingTime(shop.getPushdate(), DateUtils.getNowDay(), 1, Integer.parseInt(overDate));
        return bizTimeLastEnd;
    }

    public HashMap<String, Date> getPushDate(MtShop shop) {
        HashMap<String, Date> hashMap = new HashMap();
        Date bizTimeStart = shop.getPushdate();
        int pushDays = shop.getPushDays();
        Date bizTimeEnd = DateUtils.addDay(bizTimeStart, pushDays);
        bizTimeEnd = DateUtils.addSeconds(bizTimeEnd, -1);
        Date bizTimeLastEnd = this.getBizTimeEnd(shop);

        hashMap.put("bizTimeStart", bizTimeStart);
        hashMap.put("bizTimeEnd", bizTimeEnd);
        hashMap.put("bizTimeLastEnd", bizTimeLastEnd);
        return hashMap;
    }

    public void updateShopByPush(MtShop shop, Integer stateType, Date bizTimeEnd) {
        //5. 更新推送状态
        MtShop shopUp = new MtShop();
        shopUp.setId(shop.getId());
        shopUp.setPushState(shop.getPushState());
        shopUp.setPushState(stateType, 1);
        mtShopMapper.updateMtShop(shopUp);

        MtShop mtShop = mtShopMapper.selectMtShopById(shop.getId());
        // 判断是否全部推送完成更新同步时间
        if (mtShop.isAllPushFinished()) {
            MtShop shop1 = new MtShop();
            shop1.setId(shop.getId());
            shop1.setPushdate(DateUtils.addSeconds(bizTimeEnd, 1));
            mtShopMapper.updateMtShop(shop1);
        }
    }

    /**
     * 检查并设置当前店铺的数据拉取日期：如果当前系统日期大于店铺拉取日期并且
     * 当前日期的拉取任务都已经顺利完成，则更新当前店铺的拉取日期=拉取日期+1
     *
     * @return
     */
    public void checkAndInitPullDate(MtShop shop) {
        //延迟拉取，拉取日期最多到昨天
        Date yestoday = DateUtils.addDays(com.flow.service.utils.DateUtils.getNowDate(), -1);
        if (DateUtils.isSameDay(shop.getPulldate(), yestoday)) {
            log.info(shop.getName() + ": 当前店铺拉取日期不需要更新");
            return;
        }
        if (shop.getPulldate().getTime() > yestoday.getTime()) {
            throw new CustomException(shop.getName() + ": 拉取日期设置错误（大于昨日日期），请检查！");
        }
        if (!shop.isAllPullFinished()) {
            log.info(shop.getName() + "：数据拉取任务尚未完成！");
            return;
        }
        shop.setPulldate(DateUtils.addDays(shop.getPulldate(), 1));
        shop.setPullState(shop.init_state);
    }

    @Override
    public AjaxResult pull(MtShop mtShop) {
        log.info(mtShop.getName());
        Date pulldateEnd = mtShop.getPulldateEnd();
        mtShop = mtShopMapper.selectMtShopById(mtShop.getId());
        log.info(DateUtils.dateTime(mtShop.getPulldate()) + "---(到]---" + DateUtils.dateTime(pulldateEnd));
        MtToken mtToken = iMtTokenService.getLastTokenByConditions(new MtToken());
        long dateDiff = DateUtils.getDateDiff(pulldateEnd, mtShop.getPulldate());
        for (int i = 0; i < dateDiff; i++) {
            log.info("拉取开始"+this.getClass() + DateUtils.getTime());
            log.info("第" + (i +1) + "天");
            pullWithDay(mtShop, mtToken);
            mtShop = mtShopMapper.selectMtShopById(mtShop.getId());
            log.info("拉取结束"+this.getClass() + DateUtils.getTime());
        }
        return AjaxResult.success();
    }

//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void pullWithDay(MtShop mtShop, MtToken mtToken) {
        try {
            mtWhinService.dataPullWithShop(mtToken, mtShop);
            mtWhoutService.dataPullWithShop(mtToken, mtShop);
            if (!mtShop.getCode().startsWith("PSZX")){
                mtFoodcostcardService.dataPullWithShop(mtToken, mtShop);
                mtSalesService.dataPullWithShop(mtToken, mtShop);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage());
        }

    }
}
